
clear all;
close all;

MAX_NUM_ITER = 1000;

TFI = [ 3, 13, 12, 8, 4, 16 ];
TF = GSLpp_testfunctions();

# Test 1.: convergence analysis
for tfi = TFI
  tf = TF{tfi};
  
  if isfield(tf, "n")
    n = tf.n;
  else
    n = 0;
  endif
  
  x0 = GSLpp_get_startingpoint(tf.starting_point, n);
  x_min = GSLpp_get_minimizer(TF{tfi}.minimizer, n);
  
  results = GSLpp_minimize("gsl_ext_lrwwsimplex", struct, struct, ...
                           tf.name, struct("n", n), ...
                           struct("f", "precomp", "g", "fd", "H", "fd"), ...
                           "xdisttomin", struct("xmin", x_min, "eps", 1e-8), ...
                           x0, 0, false);

  results_disttomin = zeros(results.numiter, 1);
  results_cond = zeros(results.numiter, 1);
  results_vol = zeros(results.numiter, 1);
  plot_x = (1:results.numiter)';

  for i = 1:results.numiter
    iter = results.iterations{i};
    results_disttomin(i) = iter.stopcrit_value;
    results_cond(i) = cond(iter.E);
    results_vol(i) = iter.V;
  endfor
       
  GSLpp_newplot();
  semilogy(plot_x, results_disttomin, "linewidth", 6, ...
           plot_x, results_cond, "linewidth", 6, ...
           plot_x, results_vol, "linewidth", 6);
  axis([1, results.numiter, 1e-12, max(results_cond) * 1.1 ]);
  title(tf.title);
  legend('||x-x*||', '\kappa(E)', 'V(S)', 'location', 'southwest');
  legend("boxon");
  xlabel("iterations");
  print([ "simplex_convergence_test_", tf.name, ".ps" ], "-landscape", "-dashed", "-FArial:22");
  close;
endfor

# Test 2.: The effect of problem dimension
TFI = [ 12, 16, 13 ];

results_table = cell(length(TFI) + 1, 6);
column_widths = [ 3, 6, 14, 14, 14, 14 ];
results_table{1, 1} = 'n';
results_table{1, 2} = 'i';
results_table{1, 3} = '|g_k|';
results_table{1, 4} = 'V(S_k)';
results_table{1, 5} = '|x_k-x*|';
results_table{1, 6} = 'cond(E_k)';

for tfi = TFI
  tf = TF{tfi};
  
  row_idx = 2;
  for n = 4:4:20
    x0 = GSLpp_get_startingpoint(tf.starting_point, n);
    x_min = GSLpp_get_minimizer(TF{tfi}.minimizer, n);
      
    results = GSLpp_minimize("gsl_ext_lrwwsimplex", struct, struct, ...
                             tf.name, struct("n", n), ...
                             struct("f", "precomp", "g", "fd", "H", "fd"), ...
                             "xdisttomin", struct("xmin", x_min, "eps", 1e-8), ...
                             x0, 0, false);
    
    results_table{row_idx, 1} = n;
    results_table{row_idx, 2} = results.numiter;
    last_iter = results.iterations{results.numiter};
    results_table{row_idx, 3} = norm(last_iter.g);
    results_table{row_idx, 4} = last_iter.V;
    results_table{row_idx, 5} = norm(last_iter.x - x_min);
    results_table{row_idx, 6} = cond(last_iter.E);
    
    row_idx = row_idx + 1;
  endfor
  
  fp = fopen([ "simplex_dimension_tests_", tf.name, ".txt" ], "w");
  GSLpp_print_results_table(results_table, column_widths, fp, 'normal');
  fclose(fp);
endfor
